/**
 * 入参
 *
 */
import React, { PureComponent } from 'react';
import { PrimaryC, ModalC, PrimaryGhostC, InputC, SelectC, SecondHeaderC } from '../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, message, Switch, Modal, Spin } from 'antd';
import style from '../index.less';
import { connect } from 'dva';
import queueFun from './queueFun';
import AccountC from './accountC';
import { formSelectData, findValueByCode, fixedZeroNum } from '../../../../utils/utils';
const { confirm } = Modal;
const FormItemLayout = {
  labelCol: {
    xl: { span: 9, offset: 0 },
    xxl: { span: 6, offset: 0 },
  },
  wrapperCol: {
    xl: { span: 11, offset: 0 },
    xxl: { span: 15, offset: 0 },
  },
};
const FormItemLayout1 = {
  labelCol: {
    xl: { span: 14, offset: 0 },
    xxl: { span: 10, offset: 0 },
  },
  wrapperCol: {
    xl: { span: 10, offset: 0 },
    xxl: { span: 14, offset: 0 },
  },
};
@Form.create()
class EditConfigC extends PureComponent {
  state = {
    type: '1', //1-详情状态   2-编辑状态
    configInfo: {}, //当前配置信息
    isVisible: false, //新增节点弹窗
    newCode: undefined, //新增节点默认的组合代码
    isExtra: false, //是否有交易通道
    isTouGu: false, //是否投顾
    isAutomaticAccessInvestmentAdviser: false, // 是否自动接入投资建议
    channel: undefined, //通道标识
    approvalType: undefined, //审批类型
  };
  componentDidMount() {}
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.portfolioCode != this.props.portfolioCode) {
      this.getInfo(nextProps.portfolioCode);
    }
    if (nextProps.portfolioCode != this.props.portfolioCode && this.state.type != nextProps.type) {
      this.setState({
        type: nextProps.type,
      });
    }
  }
  //根据节点code，获取配置信息
  getInfo = (code) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'portfolioDefinitionM/queryConfigInfo',
      payload: {
        code,
      },
      callback: (data) => {
        this.setState({
          configInfo: data || {},
          channel: data && data.commandConfiguration ? this.getValue('externalChannelIdentification', data.commandConfiguration) : undefined,
          approvalType: data && data.investmentAdvisoryConfiguration ? this.getValue('investmentRecommendationApprovalType', data.investmentAdvisoryConfiguration) : undefined,
          isExtra: data && data.commandConfiguration ? true : false,
          isTouGu: data && data.investmentAdvisoryConfiguration ? true : false,
          isAutomaticAccessInvestmentAdviser: data?.investmentAdvisoryConfiguration?.isAutomaticAccessInvestmentAdviser,
        });
      },
    });
  };
  //获取审批类型 通道
  getValue = (type, data) => {
    return data[type];
  };
  onCancel = () => {
    //点击取消按钮
    const { configInfo } = this.state;
    this.setState({
      type: '1',
      // channel:undefined,//取消时 是否选中按照原数据执行
      // approvalType:undefined,
      channel: configInfo && configInfo.commandConfiguration ? this.getValue('externalChannelIdentification', configInfo.commandConfiguration) : undefined,
      approvalType:
        configInfo && configInfo.investmentAdvisoryConfiguration ? this.getValue('investmentRecommendationApprovalType', configInfo.investmentAdvisoryConfiguration) : undefined,
      isExtra: configInfo && configInfo.commandConfiguration ? true : false,
      isTouGu: configInfo && configInfo.investmentAdvisoryConfiguration ? true : false,
      isAutomaticAccessInvestmentAdviser: configInfo?.investmentAdvisoryConfiguration?.isAutomaticAccessInvestmentAdviser,
    });
  };
  saveConfig = () => {
    //保存配置项
    const {
      dispatch,
      form: { validateFields },
    } = this.props;
    validateFields((err, values) => {
      if (err) return;
      if (!this.state.isExtra) delete values.commandConfiguration; //交易通道关闭这不传
      if (!this.state.isTouGu) delete values.investmentAdvisoryConfiguration; //交易通道关闭这不传
      if (values.commandConfiguration) {
        //交易通道选中下

        if (this.state.channel !== 'NULL') {
          //当交易通道为NUll 没有账户列表
          const data = this.AccountInfo.submit(); //获取账户列表
          if (!data) return;
          values.commandConfiguration.account = data.account;
        }
      }

      dispatch({
        type: 'portfolioDefinitionM/saveSettings',
        payload: {
          ...values,
          nodeId: this.props.portfolioCode,
        },
        callback: () => {
          this.setState({
            type: '1',
          });
          this.getInfo(this.props.portfolioCode);
        },
      });
    });
  };
  addNew = () => {
    //新增子节点编号
    let newCode;
    if (this.props.treeList && this.props.portfolioCode == this.props.rootCode) {
      //如果是二级节点默认从0001开始，
      newCode = this.createCode(this.props.treeList, this.props.portfolioCode, 4);
    } else {
      //三级节点对应的二级+01，以此类推，下一级节点为上一级+01开始；组合名称为必填
      newCode = this.createCode(this.props.treeList, this.props.portfolioCode, 2);
    }
    if (!newCode) return;
    this.setState({
      isVisible: true,
      newCode,
    });
  };
  createCode = (data, node, n) => {
    // 生成新节点组合代码
    let queue = new queueFun();
    var newNode;
    var max = 0;
    queue.push(data);
    while (queue.top) {
      //遍历出所有的节点
      let item = queue.shift();
      for (let i in item.children) {
        queue.push(item.children[i]);
      }
      if (item.value == node) {
        //查询出父节点的code
        if (item.children && item.children.length > 99) {
          message.warning('每个节点的子节点数不能大于99');
          return;
        } else {
          item.children &&
            item.children.map(({ value }) => {
              if (value.split(node)[1]) {
                if (max < value.split(node)[1]) {
                  max = value.split(node)[1]; //取最大值
                }
              }
            });
        }
      }
    }
    newNode = node + fixedZeroNum(max * 1 + 1, n);
    return newNode;
  };
  //编辑
  changeEdit = () => {
    if (JSON.stringify(this.props.treeList) == '{}') return;
    this.setState({
      type: '2',
    });
  };
  //删除
  deleteByCode = () => {
    const { dispatch } = this.props;
    confirm({
      title: '是否确认删除?',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'portfolioDefinitionM/deleteNode',
          payload: {
            code: this.props.portfolioCode,
          },
          callback: () => {
            this.props.onDelete(); //删除成功通知父组件
          },
        });
      },
    });
  };
  //新增子节点弹窗
  showModal = () => {
    const { isVisible, newCode } = this.state;
    const { loading } = this.props;
    const modalProps = {
      visible: isVisible,
      title: '新增子节点',
      width: 340,
      height: 130,
      className: 'addNode',
      confirmLoading: loading.effects['portfolioDefinitionM/addNode'] === true,
    };
    return (
      <ModalC {...modalProps} onOk={this.confirmClick} onCancel={this.handleCancel}>
        <div>
          <Row>
            <Col span={24}>
              <InputC
                form={this.props.form} // form对象
                dataIndex={'portfolioCode'}
                title={'组合代码'}
                initialValue={newCode}
                rules={[{ required: true, message: '组合代码必填' }]}
                disabled={true}
              />
            </Col>
            <Col span={24}>
              <InputC
                form={this.props.form} // form对象
                dataIndex={'portfolioName'}
                title={'组合名称'}
                max={50}
                rules={[{ required: true, message: '组合名称必填' }]}
              />
            </Col>
          </Row>
        </div>
      </ModalC>
    );
  };
  confirmClick = () => {
    //弹窗确认按钮
    const {
      dispatch,
      form: { getFieldsValue, validateFields },
    } = this.props;
    validateFields(['portfolioCode', 'portfolioName', 'couseTitle'], (err, values) => {
      if (!err) {
        dispatch({
          type: 'portfolioDefinitionM/addNode',
          payload: {
            ...values,
            rootId: this.props.rootId,
            pid: this.props.portfolioCode,
          },
          callback: (data) => {
            if (data) {
              this.props.onAdd(data); //新增子节点成功 通知父组件更新页面 并定位在新节点
              this.setState({
                isVisible: false,
                newCode: undefined,
              });
            }
          },
        });
      }
    });
  };
  handleCancel = () => {
    //弹窗取消按钮
    this.setState({
      isVisible: false,
      newCode: undefined,
    });
  };
  switchChange = (checked, data) => {
    //开关变化
    this.setState({
      [data]: checked,
    });
    let nameObj = {
      isExtra: ['accountCode', 'commandConfiguration.orderUser', 'commandConfiguration.externalChannelIdentification'],
      isTouGu: [
        'investmentAdvisoryConfiguration.investmentAdviserName',
        'investmentAdvisoryConfiguration.isAutomaticAccessInvestmentAdviser',
        'investmentAdvisoryConfiguration.investmentAdvisoryAccessType',
        'investmentAdvisoryConfiguration.investmentProposalApproverUserId',
        'investmentAdvisoryConfiguration.investmentRecommendationApprovalType',
      ],
    };
    if (!checked) {
      //false清空表单
      if (data == 'isTouGu') {
        this.setState({
          isAutomaticAccessInvestmentAdviser: false,
        });
      }
      nameObj[data].map((item) => {
        if (item == 'accountCode') {
          this.AccountInfo.reset();
        }
        this.props.form.setFieldsValue({
          [item]: undefined,
        });
      });
    }
  };
  onHandleChange = (e, field) => {
    //select变更事件
    this.setState({
      [field]: e,
    });
    if (field == 'channel') {
      this.AccountInfo.reset();
    }
  };
  findValue = (id, arr) => {
    //查询出下达操作员，审批人名称
    let name;
    arr &&
      arr.map((item) => {
        if (item.value == id) {
          name = item.title;
        }
      });
    return name;
  };
  //编辑页面
  renderForm = () => {
    const {
      isExtra,
      isTouGu,
      isAutomaticAccessInvestmentAdviser,
      channel,
      configInfo: { accountConfiguration = {}, commandConfiguration = {}, investmentAdvisoryConfiguration = {} },
    } = this.state;
    const {
      form: { getFieldValue },
      globalM: { dataDictionary },
      portfolioDefinitionM: { apprpvalUserList = [], orderUserList = [] },
      isInvestment,
    } = this.props;
    return (
      <div className={style.content1}>
        <SecondHeaderC title='账户信息' topHeight={true} />
        <Row>
          <Col span={12}>
            <SelectC
              form={this.props.form} // form对象
              title='货币类型' // 显示名称
              dataIndex='accountConfiguration.currencyType' // Form识别的Item ID
              dataSource={formSelectData(dataDictionary.AccountConfigCurrencyType || [])}
              initialValue={accountConfiguration.currencyType || 'CNY'}
              showSearch={false}
              disabled={true}
              formItemLayout={FormItemLayout}
            />
          </Col>
          <Col span={12}>
            <SelectC
              form={this.props.form} // form对象
              title='资产类别控制' // 显示名称
              dataIndex='accountConfiguration.securitiesCategoryControl' // Form识别的Item ID
              dataSource={formSelectData(dataDictionary.AccountConfigSecuritiesCategoryControl || [])}
              initialValue={accountConfiguration.securitiesCategoryControl || 'ALL'}
              showSearch={false}
              formItemLayout={FormItemLayout1}
              disabled={true}
            />
          </Col>
          <Col span={12}>
            <SelectC
              form={this.props.form} // form对象
              title='市场' // 显示名称
              dataIndex='accountConfiguration.allowedMarket' // Form识别的Item ID
              dataSource={formSelectData(dataDictionary.AccountConfigAllowedMarket || [])}
              initialValue={accountConfiguration.allowedMarket || 'ALL'}
              showSearch={false}
              formItemLayout={FormItemLayout}
              disabled={true}
            />
          </Col>
          {this.props.tradeMode < 3 && (
            <Col span={12}>
              <InputC
                form={this.props.form} // form对象
                title='现金科目' // 显示名称
                dataIndex='accountConfiguration.cashAccount' // Form识别的Item ID
                max={50}
                initialValue={accountConfiguration.cashAccount || (this.props.portfolioCode == this.props.rootCode ? '银行存款_活期-银行存款' : '')}
                formItemLayout={FormItemLayout1}
                disabled={this.props.portfolioCode == this.props.rootCode}
              />
            </Col>
          )}
          <Col span={12}>
            <SelectC
              form={this.props.form} // form对象
              title='交易平台' // 显示名称
              dataIndex='accountConfiguration.tradingPlatform' // Form识别的Item ID
              dataSource={formSelectData(dataDictionary.AccountConfigTradingPlatform || [])}
              initialValue={accountConfiguration.tradingPlatform || 'ALL'}
              showSearch={false}
              disabled={true}
              formItemLayout={this.props.tradeMode < 3 ? FormItemLayout : FormItemLayout1}
            />
          </Col>
        </Row>
        {this.props.isExtra == 1 ? (
          <>
            {' '}
            <div className={style.switch}>
              <SecondHeaderC title='交易通道' topHeight={false} />
              <div>
                <Switch checked={isExtra} onChange={(checked) => this.switchChange(checked, 'isExtra')} />
              </div>
            </div>
            <Row>
              <Col span={12}>
                <SelectC
                  form={this.props.form} // form对象
                  title='通道标识' // 显示名称
                  dataIndex='commandConfiguration.externalChannelIdentification' // Form识别的Item ID
                  dataSource={formSelectData(dataDictionary.CommandConfigExternalChannelIdentification || [])}
                  initialValue={commandConfiguration.externalChannelIdentification}
                  showSearch={false}
                  onChange={(e) => this.onHandleChange(e, 'channel')}
                  rules={[{ required: isExtra, message: '通道标识必填' }]}
                  disabled={!isExtra}
                  formItemLayout={FormItemLayout}
                />
              </Col>
            </Row>
            <div style={{ display: channel == 'NULL' ? 'none' : 'inherit', marginTop: 0 }}>
              <AccountC
                data={commandConfiguration.account || [{}]} //账户信息数组 默认有一个对象
                onRef={(ref) => (this.AccountInfo = ref)}
                isExtra={isExtra}
                channel={channel}
              />
            </div>
          </>
        ) : (
          ''
        )}
        {isInvestment ? (
          <>
            <div className={style.switch} style={{ width: '130px', marginTop: '20px' }}>
              <SecondHeaderC title='投顾' topHeight={false} />
              <div>
                <Switch checked={isTouGu} onChange={(checked) => this.switchChange(checked, 'isTouGu')} />
              </div>
            </div>
            <Row>
              <Col span={12}>
                <InputC
                  form={this.props.form} // form对象
                  title='投顾名称' // 显示名称
                  dataIndex='investmentAdvisoryConfiguration.investmentAdviserName' // Form识别的Item ID
                  initialValue={investmentAdvisoryConfiguration.investmentAdviserName}
                  rules={[{ required: isTouGu, message: '投顾名称必填' }]}
                  disabled={!isTouGu}
                  formItemLayout={FormItemLayout}
                />
              </Col>
              <Col span={12}>
                <SelectC
                  form={this.props.form} // form对象
                  title='是否自动接入投资建议' // 显示名称
                  dataIndex='investmentAdvisoryConfiguration.isAutomaticAccessInvestmentAdviser' // Form识别的Item ID
                  initialValue={investmentAdvisoryConfiguration.isAutomaticAccessInvestmentAdviser}
                  isTrueFalseJudge={true}
                  showSearch={false}
                  onChange={(e) => this.onHandleChange(e, 'isAutomaticAccessInvestmentAdviser')}
                  rules={[{ required: isTouGu, message: '是否自动接入投资建议必填' }]}
                  disabled={!isTouGu}
                  formItemLayout={FormItemLayout1}
                />
              </Col>
              {isAutomaticAccessInvestmentAdviser == '1' ? (
                <>
                  <Col span={12}>
                    <SelectC
                      form={this.props.form} // form对象
                      title='接入类型' // 显示名称
                      dataIndex='investmentAdvisoryConfiguration.investmentAdvisoryAccessType' // Form识别的Item ID
                      dataSource={formSelectData(dataDictionary.InvestmentAdvisoryConfigAccessType || [])}
                      initialValue={investmentAdvisoryConfiguration.investmentAdvisoryAccessType}
                      showSearch={false}
                      rules={[{ required: isTouGu, message: '接入类型必填' }]}
                      disabled={!isTouGu}
                      formItemLayout={FormItemLayout}
                    />
                  </Col>
                  <Col span={12}>
                    <SelectC
                      form={this.props.form} // form对象
                      title='投资建议审批类型' // 显示名称
                      dataIndex='investmentAdvisoryConfiguration.investmentRecommendationApprovalType' // Form识别的Item ID
                      dataSource={formSelectData(dataDictionary.InvestmentRecommendationApprovalType || [])}
                      initialValue={investmentAdvisoryConfiguration.investmentRecommendationApprovalType}
                      showSearch={false}
                      onChange={(e) => this.onHandleChange(e, 'approvalType')}
                      rules={[{ required: isTouGu, message: '投资建议审批类型必填' }]}
                      disabled={!isTouGu}
                      formItemLayout={FormItemLayout1}
                    />
                  </Col>
                  {this.state.approvalType === 'AUTO' && (
                    <Col span={12}>
                      <SelectC
                        form={this.props.form} // form对象
                        title='自动审批人' // 显示名称
                        dataIndex='investmentAdvisoryConfiguration.investmentProposalApproverUserId' // Form识别的Item ID
                        dataSource={apprpvalUserList}
                        initialValue={investmentAdvisoryConfiguration.investmentProposalApproverUserId}
                        showSearch={false}
                        rules={[{ required: isTouGu, message: '自动审批人必填' }]}
                        disabled={!isTouGu}
                        formItemLayout={FormItemLayout}
                      />
                    </Col>
                  )}
                </>
              ) : (
                ''
              )}
            </Row>
          </>
        ) : (
          ''
        )}
      </div>
    );
  };
  render() {
    const {
      type,
      channel,
      configInfo: { accountConfiguration = {}, commandConfiguration = {}, investmentAdvisoryConfiguration = {} },
    } = this.state;
    const {
      treeList,
      nodeName,
      rootCode,
      portfolioCode,
      loading,
      globalM: { dataDictionary },
      isInvestment,
      portfolioDefinitionM: { apprpvalUserList = [], orderUserList = [] },
    } = this.props;
    return (
      <div className={style.config}>
        <div className={style.topBtn}>
          <PrimaryC title={'编辑'} onClick={this.changeEdit} disabled={type === '2'}></PrimaryC>
          {this.props.tradeMode != 4 && <PrimaryC title={'新增子节点'} onClick={this.addNew} disabled={JSON.stringify(treeList) == '{}'}></PrimaryC>}
          {JSON.stringify(treeList) == '{}' || portfolioCode == rootCode ? null : (
            <PrimaryC title={'删除'} onClick={this.deleteByCode} disabled={JSON.stringify(treeList) == '{}' || portfolioCode == rootCode}></PrimaryC>
          )}
        </div>
        <div>{nodeName || '--'}</div>
        <Spin spinning={loading.effects['portfolioDefinitionM/queryConfigInfo'] == true}>
          {type == 1 && (
            <div className={style.content}>
              <SecondHeaderC title='账户信息' topHeight={true} />
              <Row>
                <Col span={12} className={style.configRow}>
                  <span>货币类型:</span>
                  <span>{findValueByCode(accountConfiguration.currencyType, dataDictionary.AccountConfigCurrencyType)}</span>
                </Col>
                <Col span={12} className={style.configRow1}>
                  <span>资产类别控制:</span>
                  <span>{findValueByCode(accountConfiguration.securitiesCategoryControl, dataDictionary.AccountConfigSecuritiesCategoryControl)}</span>
                </Col>
                <Col span={12} className={style.configRow}>
                  <span>市场:</span>
                  <span>{findValueByCode(accountConfiguration.allowedMarket, dataDictionary.AccountConfigAllowedMarket)}</span>
                </Col>
                {this.props.tradeMode < 3 && (
                  <Col span={12} className={style.configRow1}>
                    <span>现金科目:</span>
                    <span title={accountConfiguration.cashAccount || (this.props.portfolioCode == this.props.rootCode ? '银行存款_活期-银行存款' : '--')}>
                      {accountConfiguration.cashAccount || (this.props.portfolioCode == this.props.rootCode ? '银行存款_活期-银行存款' : '--')}
                    </span>
                  </Col>
                )}
                <Col span={12} className={this.props.tradeMode < 3 ? style.configRow : style.configRow1}>
                  <span>交易平台:</span>
                  <span>{findValueByCode(accountConfiguration.tradingPlatform, dataDictionary.AccountConfigTradingPlatform)}</span>
                </Col>
              </Row>
              {JSON.stringify(commandConfiguration) !== '{}' && this.props.isExtra == 1 && (
                <>
                  <SecondHeaderC title='交易通道' topHeight={true} />
                  <Row>
                    <Col span={12} className={style.configRow}>
                      <span>通道标识:</span>
                      <span>{findValueByCode(commandConfiguration.externalChannelIdentification, dataDictionary.CommandConfigExternalChannelIdentification)}</span>
                    </Col>
                    {channel !== 'NULL' && (
                      <Col span={12} className={style.accountInfo}>
                        <div>账户信息:</div>
                        <div>
                          {commandConfiguration.account &&
                            commandConfiguration.account.map((item, key) => {
                              const str =
                                item.accountType == null && item.accountCode == null
                                  ? '--'
                                  : findValueByCode(item.accountType, channel == 'MATIC' ? dataDictionary.CommandConfigAccountName : dataDictionary.NUMBERTYPE_DICT) +
                                    '-' +
                                    item.accountCode;
                              return (
                                <div title={str} key={key}>
                                  {str}
                                </div>
                              );
                            })}
                        </div>
                      </Col>
                    )}
                  </Row>
                </>
              )}
              {JSON.stringify(investmentAdvisoryConfiguration) !== '{}' && isInvestment && (
                <>
                  <SecondHeaderC title='投顾' topHeight={true} />
                  <Row>
                    <Col span={12} className={style.configRow}>
                      <span>投顾名称:</span>
                      <span>{investmentAdvisoryConfiguration.investmentAdviserName}</span>
                    </Col>
                    <Col span={12} className={style.configRow1}>
                      <span>是否自动接入投资建议:</span>
                      <span>{investmentAdvisoryConfiguration.isAutomaticAccessInvestmentAdviser != '1' ? '否' : '是'}</span>
                    </Col>
                    {investmentAdvisoryConfiguration.isAutomaticAccessInvestmentAdviser == '1' ? (
                      <>
                        <Col span={12} className={style.configRow}>
                          <span>接入类型:</span>
                          <span>{findValueByCode(investmentAdvisoryConfiguration.investmentAdvisoryAccessType, dataDictionary.InvestmentAdvisoryConfigAccessType)}</span>
                        </Col>
                        <Col span={12} className={style.configRow1}>
                          <span>投资建议审批类型:</span>
                          <span>{findValueByCode(investmentAdvisoryConfiguration.investmentRecommendationApprovalType, dataDictionary.InvestmentRecommendationApprovalType)}</span>
                        </Col>
                        {investmentAdvisoryConfiguration.investmentRecommendationApprovalType == 'AUTO' && (
                          <Col span={12} className={style.configRow}>
                            <span>自动审批人:</span>
                            <span>{this.findValue(investmentAdvisoryConfiguration.investmentProposalApproverUserId, apprpvalUserList) || '--'}</span>
                          </Col>
                        )}
                      </>
                    ) : (
                      ''
                    )}
                  </Row>
                </>
              )}
            </div>
          )}
        </Spin>
        {type === '2' && this.renderForm()}
        <div className={style.bottomBtn}>
          {type === '2' && (
            <>
              <PrimaryGhostC title={'取消'} onClick={this.onCancel}></PrimaryGhostC>
              <PrimaryC title={'确定'} onClick={this.saveConfig} loading={this.props.loading.effects['portfolioDefinitionM/saveSettings'] === true}></PrimaryC>
            </>
          )}
          <PrimaryGhostC title={'关闭'} onClick={this.props.onClose}></PrimaryGhostC>
        </div>
        {this.state.isVisible && this.showModal()}
      </div>
    );
  }
}
export default connect(({ portfolioDefinitionM, globalM, userM: user, loading }) => ({
  portfolioDefinitionM,
  globalM,
  user,
  loading,
}))(EditConfigC);
